package org.linlinjava.litemall.mechanismadmin.web;

import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.demo.trade.model.ExtendParams;
import com.alipay.demo.trade.model.builder.AlipayTradePrecreateRequestBuilder;
import com.alipay.demo.trade.model.builder.AlipayTradeQueryRequestBuilder;
import com.alipay.demo.trade.model.result.AlipayF2FPrecreateResult;
import com.alipay.demo.trade.model.result.AlipayF2FQueryResult;
import com.alipay.demo.trade.service.AlipayTradeService;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryResult;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.pagehelper.PageInfo;
import org.linlinjava.litemall.core.alipay.config.AliPayProperties;
import org.linlinjava.litemall.core.systemConfig.SystemConfig;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.OrderUtil;
import org.linlinjava.litemall.mechanismadmin.annotation.LoginAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/mechanismadmin/goods")
public class MechanismGoodsController {
    @Autowired
    private LitemallGoodsService goodsService;
    @Autowired
    private LitemallProductService productService;
    @Autowired
    private LitemallMechanismService mechanismService;
    @Autowired
    private LitemallWalletRecordService recordService;
    @Autowired
    private PlatformTransactionManager txManager;
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private  AliPayProperties aliPayProperties;
    @Autowired
    private AlipayTradeService alipayTradeService;
    @Autowired
    private LitemallRegionService regionService;
    @Autowired
    private LitemallOrderGoodsService orderGoodsService;
    @Autowired
    private LitemallMechanismUserService litemallMechanismUserService;
    @Autowired
    private LitemallMechanismService litemallMechanismService;
    @Autowired
    private LitemallOrderService litemallOrderService;
    @Autowired
    private LitemallProductService litemallProductService;
    @Autowired
    private LitemallFreightService freightService;

    private  Map<String, Object> toVo (LitemallMechanism mdList){
        Map<String, Object> addressVo = new HashMap<>();
        String province="";
        String city="";
        String area="";
        addressVo.put("id", mdList.getId());
        addressVo.put("name",mdList.getName());
        addressVo.put("nickName",mdList.getNickName());
        addressVo.put("mechanismType",mdList.getMechanismType());
        if(mdList.getProvinceId()!=null){
            addressVo.put("provinceId",mdList.getProvinceId());
            province = regionService.findById(mdList.getProvinceId()).getName();
        }
        if(mdList.getCityId()!=null){
            addressVo.put("cityId",mdList.getCityId());
            city = regionService.findById(mdList.getCityId()).getName();
        }
        if(mdList.getAreaId()!=null){
            addressVo.put("areaId",mdList.getAreaId());
            area = regionService.findById(mdList.getAreaId()).getName();
        }
        if(mdList.getAddress()!=null){
            addressVo.put("address",mdList.getAddress());
        }
        addressVo.put("legalPerson",mdList.getLegalPerson());
        addressVo.put("telephone",mdList.getTelephone());
        addressVo.put("startTime",mdList.getStartTime());
        addressVo.put("endTime",mdList.getEndTime());
        addressVo.put("qualifications",mdList.getQualifications());
        addressVo.put("integralAmountAll",mdList.getIntegralAmountAll());
        addressVo.put("integralAmountUsed",mdList.getIntegralAmountUsed());
        addressVo.put("updateTime",mdList.getUpdateTime());
        addressVo.put("deleted",mdList.getDeleted());
        addressVo.put("province", province);
        addressVo.put("city", city);
        addressVo.put("area", area);
        return addressVo;
    }

    @GetMapping("/list")
    public Object list(
        @LoginAdmin Integer adminId,
        String name,
        @RequestParam(value = "page", defaultValue = "1") Integer page,
        @RequestParam(value = "limit", defaultValue = "10") Integer limit) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        Integer categoryId = SystemConfig.getCateGoryL2();
        List<LitemallGoods> goodsList = goodsService.querySelective(name.trim(),categoryId, page, limit);
        long total = PageInfo.of(goodsList).getTotal();

        Map<String, Object> data = new HashMap<>();
        data.put("total", total);
        data.put("items", goodsList);

        return ResponseUtil.ok(data);
    }

    @GetMapping("/detailList")
    public Object detailList(
        @LoginAdmin Integer adminId,
        Integer orderId){
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }

        LitemallGoods info = goodsService.findById(orderId);
        List<LitemallProduct> productList = productService.queryByGid(orderId);

        Map<String, Object> data = new HashMap<>();
        data.put("info", info);
        data.put("productList", productList);

        return ResponseUtil.ok(data);
    }

    /**
     * 检查有没有收货地址
     * @param adminId
     * @param mechanismId
     * @return
     */
    @GetMapping("checkout")
    public Object checkout(@LoginAdmin Integer adminId, Integer mechanismId) {
        if(adminId == null){
            return ResponseUtil.unlogin();
        }

        Map<String, Object> data = new HashMap<>();

        LitemallMechanism litemallMechanism = null;
        litemallMechanism = mechanismService.findById(mechanismId);

        if("".equals(litemallMechanism.getAddress()) || litemallMechanism.getAddress() == null){
            data.put("message", "0");
        }
        else{
            data.put("message", "1");
        }

        return ResponseUtil.ok(data);
    }

    /**
     * 微信支付
     * @param adminId
     * @param walletRecord
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/create")
    public Object create(
            @LoginAdmin Integer adminId, @RequestBody LitemallWalletRecord walletRecord, HttpServletRequest request, HttpServletResponse response) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }

        // 开启事务管理
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = txManager.getTransaction(def);
        LitemallWalletRecord checkwalletRecord = recordService.queryByRecordSn(walletRecord.getRecordSn());
        WxPayUnifiedOrderResult result = null;
        try {
            if(checkwalletRecord == null){
                walletRecord.setModifyAmount(walletRecord.getModifyAmount());
                walletRecord.setModifyTime(LocalDateTime.now());
                walletRecord.setActualPayment(walletRecord.getModifyAmount());
                walletRecord.setModifyReason("机构后台付款购买商品");
                walletRecord.setMechaismId(adminId);
                recordService.add(walletRecord);
            }
            else{
                walletRecord = checkwalletRecord;
                recordService.updatePay(walletRecord.getId());
            }

            Integer walletRecordId = walletRecord.getId();
            if(walletRecordId == null){
                return ResponseUtil.fail(-1, "订单创建失败，请重新操作！");
            }
            Integer recordId = walletRecord.getId();

            WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
            orderRequest.setProductId(recordId.toString());
            orderRequest.setOutTradeNo(walletRecord.getRecordSn());
            orderRequest.setBody("机构后台付款购买商品");
            // 元转成分
            Integer fee = 0;
            fee = walletRecord.getModifyAmount().multiply(new BigDecimal(100)).intValue();
            orderRequest.setTotalFee(fee);
            orderRequest.setSpbillCreateIp(InetAddress.getLocalHost().getHostAddress().toString());
            orderRequest.setTradeType("NATIVE");
            result = wxPayService.unifiedOrder(orderRequest);
        }
        catch (Exception ex) {
            txManager.rollback(status);
        }
        txManager.commit(status);
        return ResponseUtil.ok(result);
    }

    /**
     * 支付宝支付
     * @param adminId
     * @param walletRecord
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/chargebyalipay")
    public Object chargeByAliPay(@LoginAdmin Integer adminId, @RequestBody LitemallWalletRecord walletRecord, HttpServletRequest request, HttpServletResponse response) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }

        // 开启事务管理
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = txManager.getTransaction(def);
        LitemallWalletRecord checkwalletRecord = recordService.queryByRecordSn(walletRecord.getRecordSn());
        AlipayTradePrecreateResponse res = null;
        try {
            if(checkwalletRecord == null){
                walletRecord.setModifyAmount(walletRecord.getModifyAmount());
                walletRecord.setModifyTime(LocalDateTime.now());
                walletRecord.setActualPayment(walletRecord.getModifyAmount());
                walletRecord.setModifyReason("机构后台付款购买商品");
                walletRecord.setMechaismId(adminId);
                recordService.add(walletRecord);
            }
            else{
                walletRecord = checkwalletRecord;
                recordService.updatePay(walletRecord.getId());
            }
            Integer mechanismId = walletRecord.getModifyResource();

            //商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no = walletRecord.getRecordSn();
            //付款金额，必填
            String total_amount = walletRecord.getModifyAmount().toString();
            //订单名称，必填
            String subject = new String(walletRecord.getModifyReason().getBytes("UTF-8"), "UTF-8");
            //商品描述，可空
            String body = new String("");
            //            String sign_type = "RSA2";
            String timeoutExpress = "15m";

            ExtendParams extendParams = new ExtendParams();
            extendParams.setSysServiceProviderId(aliPayProperties.getPid());

            AlipayTradePrecreateRequestBuilder builder =
                    new AlipayTradePrecreateRequestBuilder().setSubject(subject).setTotalAmount(total_amount).setOutTradeNo(out_trade_no).setBody(body).setTimeoutExpress(timeoutExpress)
                            .setAppAuthToken(aliPayProperties.getAppAuthToken()).setStoreId(mechanismId.toString())
                            //支付宝服务器主动通知商户服务器里指定的页面http路径,根据需要设置
                            .setNotifyUrl(aliPayProperties.getNotifyUrl()).setExtendParams(extendParams);
            AlipayF2FPrecreateResult preCreateResult = alipayTradeService.tradePrecreate(builder);
            switch (preCreateResult.getTradeStatus()) {
                case SUCCESS:
                    res = preCreateResult.getResponse();
                    break;
                case FAILED:
                case UNKNOWN:
                    return ResponseUtil.fail(-1, "支付宝预下单失败");
                default:
                    return ResponseUtil.fail(-1, "支付宝预下单失败");
            }

        }
        catch (Exception ex) {
            txManager.rollback(status);
            return ResponseUtil.fail(-1, "支付出错!");
        }
        txManager.commit(status);
        return ResponseUtil.ok(res.getQrCode());
    }

    /**
     * 生成订单
     * @param adminId
     * @param orderSn
     * @param goodId
     * @param goodsprice
     * @param mechanismId
     * @param number
     * @param finalProductId
     * @param goodsname
     * @param goodsSn
     * @return
     */
    @GetMapping("/addOrder")
    public Object addOrder(@LoginAdmin Integer adminId, String orderSn,Integer goodId, BigDecimal goodsprice, BigDecimal freight, Integer mechanismId, Short number,Integer finalProductId, String goodsname, String goodsSn){
        LitemallMechanismUser litemallMechanismUser = litemallMechanismUserService.findById(adminId);
        LitemallMechanism litemallMechanism =litemallMechanismService.findById(mechanismId);
        Map<String, Object> addressVo = toVo(litemallMechanism);
        String address = addressVo.get("province")+" "+addressVo.get("city")+" "+addressVo.get("area")+" "+litemallMechanism.getAddress();
        LitemallOrder order= new LitemallOrder();
        order.setOrderStatus(OrderUtil.STATUS_CREATE);
        order.setUserId(adminId);
        order.setOrderSn(orderSn);
        order.setConsignee(litemallMechanism.getLegalPerson());
        order.setMobile(litemallMechanism.getTelephone());
        order.setAddress(address);
        order.setGoodsPrice(goodsprice);
        order.setFreightPrice(freight);
        order.setOrderPrice(goodsprice.add(freight));
        order.setActualPrice(goodsprice.add(freight));
        order.setAddTime(LocalDateTime.now());
        order.setActualIntegral(0);
        order.setMechanismType(true);
        order.setGivePrice(new BigDecimal(0));
        order.setGiveIntegral(0);
        litemallOrderService.add(order);

        LitemallProduct litemallProduct = litemallProductService.findById(finalProductId);

        LitemallOrderGoods litemallOrderGoods = new LitemallOrderGoods();
        litemallOrderGoods.setAddTime(LocalDateTime.now());
        litemallOrderGoods.setGoodsId(goodId);
        litemallOrderGoods.setOrderId(order.getId());
        litemallOrderGoods.setProductId(finalProductId);
        litemallOrderGoods.setNumber(number);
        litemallOrderGoods.setPicUrl(litemallProduct.getUrl());
        litemallOrderGoods.setSpecifications(litemallProduct.getSpecifications());
        litemallOrderGoods.setGoodsName(goodsname);
        litemallOrderGoods.setGoodsSn(goodsSn);
        litemallOrderGoods.setPrice(litemallProduct.getPrice());
        litemallOrderGoods.setIntegral(0);
        litemallOrderGoods.setPriceFlag(Byte.parseByte("1"));
        litemallOrderGoods.setIntegralFlag(Byte.parseByte("1"));
        orderGoodsService.add(litemallOrderGoods);

        return ResponseUtil.ok();
    }

    /**
     * 检查微信支付结果
     * @param adminId
     * @param orderSn
     * @return
     */
    @GetMapping("/checkchargestatus")
    public Object checkChargeStatus(@LoginAdmin Integer adminId, String orderSn) {
        Map<String, Object> data = new HashMap<>();
        try {
            WxPayOrderQueryResult orderQueryResult = wxPayService.queryOrder("", orderSn);
            String returnCode = orderQueryResult.getReturnCode();
            String resultCode = orderQueryResult.getResultCode();
            String tradeState = orderQueryResult.getTradeState();
            if (returnCode.equals("SUCCESS") && resultCode.equals("SUCCESS") && tradeState.equals("SUCCESS")) {
                data.put("orderStatus", "SUCCESS");
                // 开启事务管理
                LitemallWalletRecord walletRecord = recordService.queryByRecordSn(orderSn);
                DefaultTransactionDefinition def = new DefaultTransactionDefinition();
                def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
                TransactionStatus status = txManager.getTransaction(def);
                try {
                    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
                    LocalDateTime ldt = LocalDateTime.parse(orderQueryResult.getTimeEnd(), df);
                    walletRecord.setPayId(orderQueryResult.getTransactionId());
                    walletRecord.setPayTime(ldt);
                    recordService.update(walletRecord);
                    LitemallOrder order = litemallOrderService.queryByOrderSn(orderSn);
                    order.setPayId(orderQueryResult.getTransactionId());
                    order.setPayTime(ldt);
                    order.setOrderStatus(OrderUtil.STATUS_PAY);
                    litemallOrderService.update(order);
                }
                catch (Exception ex) {
                    txManager.rollback(status);
                }
                txManager.commit(status);
            } else {
                data.put("orderStatus", "FAIL");
            }
        }
        catch (WxPayException e) {
            e.printStackTrace();
        }
        return ResponseUtil.ok(data);
    }

    /**
     * 检查支付宝支付结果
     * @param adminId
     * @param orderSn
     * @return
     */
    @GetMapping("/checkalipaystatus")
    public Object checkAliPayStatus(@LoginAdmin Integer adminId, String orderSn) {
        Map<String, Object> data = new HashMap<>();
        try {
            AlipayTradeQueryRequestBuilder builder = new AlipayTradeQueryRequestBuilder().setOutTradeNo(orderSn).setAppAuthToken(aliPayProperties.getAppAuthToken());
            AlipayF2FQueryResult queryResult = alipayTradeService.queryTradeResult(builder);
            System.out.println(queryResult);
            AlipayTradeQueryResponse response = queryResult.getResponse();
            switch (queryResult.getTradeStatus()) {
                case SUCCESS:
                    System.out.println("查询返回该订单支付成功:");
                    //                log.info(resp.getFundBillList());
                    if (response.getTradeStatus().equals("TRADE_SUCCESS") || response.getTradeStatus().equals("TRADE_FINISHED")) {
//                        System.out.println("支付成功");
                        data.put("orderStatus", "SUCCESS");
                        // 开启事务管理
                        LitemallWalletRecord walletRecord = recordService.queryByRecordSn(orderSn);
                        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
                        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
                        TransactionStatus status = txManager.getTransaction(def);
                        try {
                            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
                            LocalDateTime ldt = LocalDateTime.ofInstant(response.getSendPayDate().toInstant(), ZoneId.systemDefault());
                            walletRecord.setPayId(response.getTradeNo());
                            walletRecord.setPayTime(ldt);
                            recordService.update(walletRecord);
                            LitemallOrder order = litemallOrderService.queryByOrderSn(orderSn);
                            order.setPayId(response.getTradeNo());
                            order.setPayTime(ldt);
                            order.setOrderStatus(OrderUtil.STATUS_PAY);
                            litemallOrderService.update(order);
                        }
                        catch (Exception ex) {
                            txManager.rollback(status);

                            return ResponseUtil.fail();
                        }
                        txManager.commit(status);
                    } else if (response.getTradeStatus().equals("WAIT_BUYER_PAY")) {
//                        System.out.println("等待成功");
                        data.put("orderStatus", "WAIT_PAY");
                    } else {
                        data.put("orderStatus", "FAIL");
                    }
                    break;
                case FAILED:
                    // log.error("查询返回该订单支付失败!!!");
                    data.put("orderStatus", "WAIT_PAY");
                    break;
                case UNKNOWN:
                    //                    log.error("系统异常，订单支付状态未知!!!");
                    return ResponseUtil.fail(-1, "系统异常，订单支付状态未知!!!");
                default:
                    //                    log.error("不支持的交易状态，交易返回异常!!!");
                    return ResponseUtil.fail(-1, "不支持的交易状态，交易返回异常!!!");
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.fail();
        }
        return ResponseUtil.ok(data);
    }

    @GetMapping("/detail")
    public Object detail(@LoginAdmin Integer adminId, Integer mechanismId, Integer id, Integer number, Integer orderId) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }

        if (mechanismId == null) {
            return ResponseUtil.badArgument();
        }

        Integer unifyNumber = null;

        LitemallOrderGoods litemallOrderGoods = null;
        LitemallProduct product = null;
        if(!"".equals(orderId) && orderId != null){
            litemallOrderGoods = orderGoodsService.queryByOid(id).get(0);
            product = productService.findById(litemallOrderGoods.getProductId());
            unifyNumber = Integer.parseInt(litemallOrderGoods.getNumber().toString());
        }
        else{
            product = productService.findById(id);
            unifyNumber = number;
        }
        LitemallMechanism mechanism = mechanismService.findById(mechanismId);
        BigDecimal[] freight = new BigDecimal[2];
        freight = getFreight(product, mechanism, unifyNumber);
        //LitemallMechanismUser litemallMechanismUser = litemallMechanismUserService.queryByMechanismId(mechanismId);
        int num = litemallMechanismUserService.num(mechanismId);
        Map<String, Object> data = new HashMap<>();
        //data.put("user", litemallMechanismUser);
        data.put("num", num);
        data.put("checkedGoodsPrice", freight[0]);
        data.put("freightPrice", freight[1]);
        return ResponseUtil.ok(data);
    }

    private String detailedAddress(Integer provinceId, Integer cityId, Integer areaId, String address) {
        String provinceName = regionService.findById(provinceId).getName();
        String cityName = regionService.findById(cityId).getName();
        String areaName = regionService.findById(areaId).getName();
        String fullRegion = provinceName + " " + cityName + " " + areaName;
        return fullRegion + " " + address;
    }

    private BigDecimal[] getFreight(LitemallProduct product, LitemallMechanism mechanism, Integer number){
        int goodsTotalWeight = product.getWeight()*number;//订单全部商品重量，单位为g

        BigDecimal checkedGoodsPrice = new BigDecimal(0.00);//订单商品总售价

        checkedGoodsPrice = checkedGoodsPrice.add(product.getPrice().multiply(new BigDecimal(number)));

        /*计算收货地址运费标准开始*/
        BigDecimal freightPrice = new BigDecimal(0.00);//运费

        LitemallRegion litemallRegion = null;

        String provinceName = "";//收货地址的省级地区名称

        Integer freightCode = null;//取收货地址的省级code或者市级code

        int startingPrice = 0;//收货地址所在地区的起步价（重量少于3kg所需运费）

        int overWeightPrice = 0;//收货地址所在地区的超重价（超过3kg的部分每kg所需运费）

        //根据地区code查询
        litemallRegion = regionService.findById(mechanism.getProvinceId());

        if(litemallRegion != null){
            provinceName = litemallRegion.getName();
        }

        //判断收货地址是否是内蒙古自治区
        if("内蒙古自治区".equals(provinceName)){
            freightCode = mechanism.getCityId();//如果收货地址的省份是内蒙古自治区，取收货地址的市级code
        }
        else{
            freightCode = mechanism.getProvinceId();//如果收货地址的省份不是内蒙古自治区，取收货地址的省级code
        }

        LitemallFreight litemallFreight = null;

        if(freightCode != null){
            litemallFreight = freightService.selectByCode(freightCode);
            startingPrice = litemallFreight.getStartingPrice();//得到收货地址所在地区的起步价(3kg以内)
            overWeightPrice = litemallFreight.getOverWeightPrice();//得到收货地址所在地区的超重价(每kg)
        }
        /*计算收货地址运费标准结束*/

        /*计算订单总运费开始*/
        double freightDecimal = 0.0;//运费保留小数点的价格
        //特殊商品
        if(product.getSpecialtyGoods()){
            if(goodsTotalWeight > 0){
                freightPrice = freightPrice.add(new BigDecimal(startingPrice));
            }
            //如果商品的重量超过3000g
            if(goodsTotalWeight > 3000){
                freightDecimal = overweightRate(goodsTotalWeight, overWeightPrice);//计算全部商品超重价
                freightPrice = freightPrice.add(new BigDecimal(freightDecimal));
            }
        }
        //非特殊商品
        else{
            //如果订单总价不满足88人民币，这里不需要考虑商品的重量
            if(checkedGoodsPrice.compareTo(new BigDecimal(88)) == -1){
                if(goodsTotalWeight > 0){
                    freightPrice = freightPrice.add(new BigDecimal(startingPrice));
                }
                //如果商品的重量超过3000g
                if(goodsTotalWeight > 3000){
                    freightDecimal = overweightRate(goodsTotalWeight, overWeightPrice);//计算商品超重价
                    freightPrice = freightPrice.add(new BigDecimal(freightDecimal));
                }
            }
            //如果订单总价满足88人民币，不作判断（包邮）
            //else{}
        }
        /*计算订单总运费结束*/

        checkedGoodsPrice = checkedGoodsPrice.add(freightPrice);//商品价格加上邮费
        BigDecimal[] bigDecimal = new BigDecimal[2];
        bigDecimal[0] = checkedGoodsPrice;
        bigDecimal[1] = freightPrice;

        return bigDecimal;
    }

    /**
     * 超重价计算
     * @param weight
     * @param overWeightPrice
     * @return
     */
    private double overweightRate(int weight, int overWeightPrice){
        return new BigDecimal((float)(weight-3000)/1000).setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue()*overWeightPrice;//运费四舍五入
    }
}